<?php
namespace app\api\service;
use think\Request;
use app\api\model\Staff;
use app\api\model\Contact;
use app\api\model\Postion;

class StaffService {
    public function page($page = 1, $size = 10){
        $data 	= Request::instance()->get();
        $where 	= [];

        empty($data['position']) || $where['position'] = $data['position'];
        empty($data['name']) || $where['name'] = ['like','%'.$data['name']];

        $obj = Staff::with(['fposition', 'fcontact'])->where($where)
        ->paginate($size, false, ['page' => $page]);

        if ($obj->isEmpty()){
            return [];
        }
        return $obj->toArray();
    }

    public function save(){ 
        $param = Request::instance()->param();	//获取参数

        if (!is_numeric($param['id']))
        {
            if (!isset($param['contact'])) {
                return show(0, '错误', [], 200);
            }
            // 新增
            $staff = new Staff;
            $staff->name     = $param['name'];
            $staff->contact  = $param['contact'];
            $staff->position = $param['position'];

            if( $staff->save()){
                return show(1, '新增成功', [], 200);
            }
        }else {
            // 更新
            $staff = Staff::get($param['id']);
            $staff->name = $param['name'];
            $staff->position = $param['position'];
            // 检测错误
            if( $staff->save()){
                return show(1, '修改成功', [], 200);
            }
        }
        
        return show(0, '修改失败', [], 200);
    }

    public function delete($id){

    	if( Staff::destroy($id, true) ){
            return show(1, '删除成功', [], 200);
        }
        
        return show(0, '删除失败', [], 200);
    }
}